import {defineComponent, ref, watch} from 'vue';
import {Table} from 'ant-design-vue';
import type {TableColumnType} from 'ant-design-vue/lib/table/interface';

interface TableProps<T> {
    value?: T[];
    columns: TableColumnType<T>[];
}

export default defineComponent({
    name: 'AntdTable',
    props: {
        value: {
            type: Array,
            default: () => []
        },
        columns: {
            type: Array,
            required: true
        }
    },
    emits: ['update:value'],
    setup(props, {emit}) {
        const tableData = ref([...props.value]);

        // Watch for changes from the parent component (v-model)
        watch(
            () => props.value,
            (newValue) => {
                tableData.value = [...newValue];
            }
        );

        // Update v-model when table data changes
        const updateTableData = (newData: any[]) => {
            tableData.value = [...newData];
            emit('update:value', newData); // Emit the update:value event for v-model
        };

        return () => (
            <Table
                columns={props.columns}
                dataSource={tableData.value}
                rowKey="id"
                pagination={false}
                onChange={(pagination, filters, sorter, extra) => {
                    // You can handle any additional table events here
                    console.log('Table changed: ', extra.currentDataSource);
                    updateTableData(extra.currentDataSource);
                }}
            />
        );
    }
});